﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Web.Services;
using BLL;
using Model;
using System.Web.Security;

/// <summary>
///ViewENAState 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。 
// [System.Web.Script.Services.ScriptService]
public class ViewENAState : System.Web.Services.WebService
{
    Microsoft.VisualBasic.Devices.Computer com = new Microsoft.VisualBasic.Devices.Computer();
    private static int pcount, fcount;
    private static List<ENAInfo> eNAs;
    private static List<ENAInfo> eNAInfos;
    ENA eNA;

    public ViewENAState()
    {
        eNA = new ENA();
        eNAInfos = (List<ENAInfo>)eNA.GetENAs();
        //如果使用设计的组件，请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public List<ENAInfo> ENAMonitor(out int p, out int f)
    {
        PingENA();
        p = pcount;
        f = fcount;
        return eNAs;
    }

    [WebMethod]
    public bool ValidUser(string username, string password)
    {
        return Membership.ValidateUser(username, password);
    }

    [WebMethod]
    public bool ValidRole(string username)
    {
        string[] rs = Roles.GetRolesForUser(username);
        string[] validrs = { "Administrators", "Manager", "IT Engineer" };
        foreach(string str in rs)
        {
            foreach(string str1 in validrs)
                if(str==str1)
                {
                    return true;
                }
        }
        return false;
    }

    public void PingENA()
    {
        pcount = 0;
        fcount = 0;
        eNAs = new List<ENAInfo>();
        int i;
        int n = eNAInfos.Count;
        Thread[] thr = new Thread[n];
        for (i = 0; i < n; i++)
        {
            thr[i] = new Thread(new ParameterizedThreadStart(Ping));
            thr[i].Start(i);
        }
        for (int j = 0; j < n; j++)
        {
            thr[j].Join();
        }
    }

    protected void Ping(object o)
    {
        int i = Convert.ToInt32(o);
        bool result = com.Network.Ping(eNAInfos[i].ENAIP);
        if (result == true)
        {
            Interlocked.Increment(ref pcount);
        }
        else
        {
            Interlocked.Increment(ref fcount);
            lock (eNAs)
            {
                eNAs.Add(eNAInfos[i]);
            }
        }
    }
}

